$(document).ready(function () {
    var userstring = sessionStorage.getItem('user');
    var user = JSON.parse(userstring);
    var nickname = user.nickname;
    $('#nickname').text(nickname);

    var sid=1;
    var pid = 1;

    //根据uid查询地址
    var uid = user.id;
    $.get("pc/address/find", {"uid": uid}, function (rs) {
        var pros = rs.result;
        var dl = $("dl[name='u_address']");
        dl.empty();
        dl.append('<dt>寄送到：</dt>');
        for (var i = 0; i < pros.length; i++) {
            var address = pros[i];
            var addressHtml = "<dd><input type='radio' name='address'  value='" + i + "' " + (i === 0 ? "checked" : "") + " >" +
                address.detailedAddress + ' ' + "(" + address.sname + " 收 )" + address.phone + "</dd>";
            $(addressHtml).appendTo(dl);
        }
        dl.on('change', 'input[type="radio"][name="address"]', function () {
            var add = $(this).val();
            sid = pros[add].id;
            alert(sid);
        });
    });
    $(document).on("change", 'input[type="radio"][name="pay_style"]', function () {
        pid = $(this).val();
        alert(pid);
    });

    $("[class='goods_list_td clearfix']").empty();
    var objs = sessionStorage.getItem("loc")
    var obj = JSON.parse(objs);
    console.log(obj);
    console.log(obj[0].fname)
    /*var obj=JSON.parse(objs);
    console.log(obj);*/

    var sum = 0;
    var count = 0;
    for (var i = 0; i < obj.length; i++) {
        $("<ul class=\"goods_list_td clearfix\">\n" +
            "        <li class=\"col01\">" + (i + 1) + "</li>\n" +
            "        <li class=\"col02\"><img src=\"" + obj[i].image + "\"></li>\n" +
            "        <li class=\"col03\" value='" + obj[i].fname + "'>" + obj[i].fname + "</li>\n" +
            "        <li class=\"col04\">500g</li>\n" +
            "        <li class=\"col05\">" + obj[i].price + "元</li>\n" +
            "        <li class=\"col06\">" + obj[i].quantity + "\n" +
            "        <li class=\"col07\">" + obj[i].amount + "元</li>\n" +
            "    </ul>").appendTo("#listt");
        sum += obj[i].amount;
        count++;
    }
    var id;
    var i;
    $("#sum").text("" + sum + "元");
    $("#count").text(count);
    $("#sum1").text("" + (sum + 10) + "元");
    //alert("到函数前面了");
    $("#order_btn").click(function () {
        //alert("点击了");
        //添加订单
        $.get("order/addOrder", {
            "sid": sid,
            "status": "B",
            "amount": sum,
            "pid": pid,
            "uid": uid
        }, function (b) {
            if (b) {
                //添加订单项
                //循环中嵌套异步操作，可能导致并发问题和顺序不可控。当数组长度较大时，可能会同时发送多个请求，使得处理顺序难以确定。
                /*for (i = 0; i < obj.length; i++) {
                    id = obj[i].id;
                    alert(id);
                    var quantity = obj[i].quantity;
                    var price = obj[i].amount;
                    console.log(quantity);
                    //添加订单项
                    $.get("orderitem/addOrderItems", {"fid": id, "quantity": quantity, "price": price}, function (bo) {
                        if (bo) {
                            //删除购物车
                            $.get("order/removeShoppingTrolley", {"id": id}, function (boo) {
                                if (boo && i === obj.length - 1) {
                                    localStorage.setItem('order_finish', 2);
                                    $('.popup_con').fadeIn('fast', function () {
                                        setTimeout(function () {
                                            $('.popup_con').fadeOut('fast', function () {
                                                window.location.href = 'list.html';
                                            });
                                        }, 3000)
                                    });
                                } else {
                                    alert("失败了！！");
                                }
                            });
                        } else {
                            alert("失败了！！")
                        }
                    });
                }*/
                processItems(obj);

            } else {
                alert("失败了！！");
            }
        });
    });
});
//异步函数
async function processItems(obj) {
    try {
        const promises = [];
        for (let i = 0; i < obj.length; i++) {
            const id = obj[i].fid;
            const quantity = obj[i].quantity;
            const price = obj[i].amount;
            // 添加订单项的异步操作封装为 Promise
            const addPromise = new Promise((resolve, reject) => {
                $.get("orderitem/addOrderItems", { "fid": id, "quantity": quantity, "price": price }, function (bo) {
                    if (bo) {
                        resolve();
                    } else {
                        reject(`添加订单项失败，id: ${id}`);
                    }
                });
        });
            promises.push(addPromise);
        }
        // 等待所有添加订单项的请求完成
        await Promise.all(promises);
        const removePromises = [];
        for (let i = 0; i < obj.length; i++) {
            const id = obj[i].id;
            // 删除购物车项的异步操作封装为 Promise
            const removePromise = new Promise((resolve, reject) => {
                $.get("order/removeShoppingTrolley", { "id": id }, function (boo) {
                    if (boo) {
                        resolve();
                    } else {
                        reject(`删除购物车项失败，id: ${id}`);
                    }
                });
        });
            removePromises.push(removePromise);
        }
        // 等待所有删除购物车项的请求完成
        await Promise.all(removePromises);
        localStorage.setItem('order_finish', 2);
        $('.popup_con').fadeIn('fast', function () {
            setTimeout(function () {
                $('.popup_con').fadeOut('fast', function () {
                    window.location.href = 'list.html';
                });
            }, 3000);
        });
    } catch (error) {
        console.error(error);
        alert(`操作失败：${error}`);
    }
}